package com.yiqi.news.mvp.ui.activity

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.os.Message
import android.support.v4.app.Fragment
import android.util.Log
import android.view.KeyEvent
import com.flyco.tablayout.listener.CustomTabEntity
import com.flyco.tablayout.listener.OnTabSelectListener

import com.jess.arms.base.BaseActivity
import com.jess.arms.base.BaseApplication
import com.jess.arms.di.component.AppComponent
import com.jess.arms.utils.ArmsUtils
import com.jess.arms.utils.LogUtils
import com.socks.library.KLog
import com.yiqi.news.R
import com.yiqi.news.app.EventBusTags
import com.yiqi.news.app.service.UploadTimeOnlineService
import com.yiqi.news.app.service.UserController
import com.yiqi.news.app.utils.SPUtil
import com.yiqi.news.app.utils.SPUtil.SP_NAME
import com.yiqi.news.app.utils.TimeUtils
import com.yiqi.news.di.component.DaggerMainComponent
import com.yiqi.news.di.module.MainModule
import com.yiqi.news.mvp.contract.MainContract
import com.yiqi.news.mvp.presenter.MainPresenter
import io.reactivex.Observable
import kotlinx.android.synthetic.main.activity_main.*
import java.util.ArrayList
import io.reactivex.disposables.Disposable
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import org.simple.eventbus.EventBus
import java.util.concurrent.TimeUnit


class MainActivity : BaseActivity<MainPresenter>(), MainContract.View {

    private var mSubscribe: Disposable? = null

    private val receiver: TimeOnlineReceiver by lazy {
        return@lazy TimeOnlineReceiver()
    }

    override fun setupActivityComponent(appComponent: AppComponent) {
        DaggerMainComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .mainModule(MainModule(this))
                .build()
                .inject(this)
    }


    override fun initView(savedInstanceState: Bundle?): Int {
        return R.layout.activity_main //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val intentFilter = IntentFilter()
        intentFilter.addAction("UPLOADTIMEONLINE.ACTION")
        registerReceiver(receiver, intentFilter)
    }

    override fun initData(savedInstanceState: Bundle?) {
        mPresenter?.requestTab()
    }

    override fun launchActivity(intent: Intent) {
        ArmsUtils.startActivity(intent)
    }

    override fun killMyself() {
        finish()
    }

    override fun initTab(fragments: Array<Fragment>, tabLayout: ArrayList<CustomTabEntity>) {
        tab_home.setTabData(tabLayout, this, R.id.fl_change, fragments.toList() as ArrayList<Fragment>)
        tab_home.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabSelect(position: Int) {

                if (position == 2 && !UserController.getInstance().isLogin) {
                    ArmsUtils.startActivity(LoginActivity::class.java)
                    tab_home.currentTab = 0
                }
            }

            override fun onTabReselect(position: Int) {

            }
        })
    }


    //开始轮询
    private fun startTime() {
        //interval对应参数 ：首次执行延时时间 、 每次轮询间隔时间 、 时间类型
        mSubscribe = Observable.interval(0, 60, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .subscribe {
                    mPresenter?.requestOnLine()
                }
    }

    override fun onDestroy() {
        super.onDestroy()
        mSubscribe?.let { if (!it.isDisposed) it.dispose() }
        unregisterReceiver(receiver)
    }

    override fun onLineStop() {
        SPUtil.put(baseContext, SP_NAME, TimeUtils.getTodayStartTime().toString(), 0L)

        EventBus.getDefault().post(Message(), EventBusTags.NEED_UPDATE_DATA)
        mSubscribe?.let { if (!it.isDisposed) it.dispose() }
    }


    override fun useImmersionBar(): Boolean? = true

    override fun showMessage(message: String) {

    }


    private var exitTime: Long = 0
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN) {
            if (System.currentTimeMillis() - exitTime > 2000) {
                ArmsUtils.snackbarText("再按一次退出聚财赚")
                exitTime = System.currentTimeMillis()
            } else {
                finish()
                ArmsUtils.exitApp()
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }


    inner class TimeOnlineReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            mPresenter?.requestOnLine()
            val timeIntent = Intent(this@MainActivity, UploadTimeOnlineService::class.java)
            startService(timeIntent)
        }


    }

}
